package com.xiaoyong.file.FileController;

import com.xiaoyong.entity.Result;
import com.xiaoyong.entity.StatusCode;
import com.xiaoyong.file.pojo.FastDFSFile;
import com.xiaoyong.file.util.FastDFSClient;
import io.netty.util.internal.StringUtil;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.IOException;

@RestController
@RequestMapping("/file")
public class FileController {

    @PostMapping("/upload")
    public Result uploadFile(MultipartFile file){
        try {
        //判断文件是否存在
        if (file==null){
            throw new RuntimeException("文件不存在");
        }
        //获取文件完整名称
        String originalFilename = file.getOriginalFilename();
        if (StringUtils.isEmpty(originalFilename)){
            throw new RuntimeException("文件不存在");
        }
        //获取文件的扩展名 abc.jpg
        String substring = originalFilename.substring(originalFilename.lastIndexOf(".") + 1);
        //获取文件内容
            byte[] bytes = file.getBytes();
            //上传文件封装的实体类
            FastDFSFile fastDFSFile = new FastDFSFile(originalFilename, bytes, substring);
            //基于工具类进行文件上传，并接受返回参数 String[]
            String[] uploadResult = FastDFSClient.upload(fastDFSFile);
            //封装返回结果
           String url= FastDFSClient.getTrackerUrl()+uploadResult[0]+"/"+ uploadResult[1];
           return new Result(true, StatusCode.OK,"封装成功",url);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return new Result(false,StatusCode.ERROR,"文件上传失败");
    }
}
